//
//  HomePageViewController.m
//  TheEyesShop
//
//  Created by 杜文杰 on 2017/10/14.
//  Copyright © 2017年 dwj. All rights reserved.
//

#import "HomePageViewController.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件
#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引入检索功能所有的头文件
#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>//引入云检索功能所有的头文件
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>//引入计算工具所有的头文件
#import <BaiduMapAPI_Radar/BMKRadarComponent.h>//引入周边雷达功能所有的头文件
#import <BaiduMapAPI_Map/BMKMapView.h>//只引入所需的单个头文件
#import <CoreLocation/CoreLocation.h>

#import "HomePageTitleView.h"
#import "CityListViewController.h"
#import "MineView.h"
#import "LoginViewController.h"
#import "MineOrderViewController.h"
#import "OverInfomationViewController.h"
#import "ReleaseServerViewController.h"
#import "SendedJobListViewController.h"
#import "MyAssetsViewController.h"
#import "MessageAndTalkAboutViewController.h"
#import "MineManagerHomeViewController.h"
#import "SetSystemInfomationViewController.h"
#import "DetailMakeSureViewController.h"
#import "YXSearchServersListViewController.h"
#import "SendServersListViewController.h"
#import "SCGIFImageView.h"
#import <UShareUI/UShareUI.h>
#import <UMSocialCore/UMSocialCore.h>
#import "WJListMenuViewController.h"
#import "JZLocationConverter.h"

static MineView *mineView;
#define TITLEVIEW_HEIGHT 60

@interface HomePageViewController ()<BMKMapViewDelegate, BMKPoiSearchDelegate,CityListViewDelegate,CLLocationManagerDelegate>
{
    BMKMapView *_mapView;
    BMKPoiSearch *_searcher;
    BMKGeoCodeSearch *geoCodeSearch;
}
@property (nonatomic, strong) NSString *titleNameStr;
@property (nonatomic, strong) HomePageTitleView *titleView;
@property (nonatomic, strong) NSString *currentCityStr;
@property (nonatomic, assign) double latitude;// 维度
@property (nonatomic, assign) double longitude;// 经度
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, assign) NSMutableArray *dataArray;
@property (nonatomic, assign) int indexInter;
@property (nonatomic, strong) NSDictionary *userDataDic;
@property (nonatomic, assign) int subtype;
@end

@implementation HomePageViewController
// 获取用户信息
- (void)getInfoMations {
    if ([[UserModel sharedInstanced].userId isEqualToString:@""] || ![UserModel sharedInstanced].userId) {
        return;
    }
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=userinfo" parameters:@{@"uid":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"error_code"]];
        if ([str isEqualToString:@"0"]) {
            NSDictionary *dataDic = responseObject[@"data"];
            if (dataDic[@"avatar"] != NULL || dataDic[@"avatar"] != nil) {
                [UserModel sharedInstanced].headImg = dataDic[@"avatar"]; // 头像
            }
            if (dataDic[@"nickname"] != NULL || dataDic[@"nickname"] != nil) {
                [UserModel sharedInstanced].nameNick = dataDic[@"nickname"]; // 昵称
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //        [self showError:error];
    }];
}
/**
 获取服务的经纬度  根据经纬度显示大头针
 */
- (void)getImagesInfo {
    NSDictionary *parameter = @{@"lat":[NSString stringWithFormat:@"%f",self.latitude],@"lnt":[NSString stringWithFormat:@"%f",self.longitude]};
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=indexico" parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"error_code"] isEqualToString:@"0"]) {
//            ShowMessage(@"操作成功");
            //NSArray *array = responseObject[@"data"];
            self.dataArray = responseObject[@"data"];
            for (NSDictionary *dic in self.dataArray) {
                BMKPointAnnotation* annotation = [[BMKPointAnnotation alloc]init];
                CLLocationCoordinate2D coor;
                coor.latitude = [dic[@"icolat"] doubleValue];
                coor.longitude = [dic[@"icolnt"] doubleValue];
                annotation.coordinate = coor;
                annotation.title = dic[@"icotitle"];
//                annotation.subtitle = @"这里是北京颐和园";
                [_mapView   addAnnotation:annotation];
            }
        }
        ShowMessage(responseObject[@"message"]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
/**
 参数名    必选    类型    说明
 lat    是    string    维度
 lnt    是    string    经度
 user_id    是    string    用户id
 token    是    string    用户令牌
 */
- (void)postLatAndLongToServer {
    NSDictionary *parameter = @{@"lat":[NSString stringWithFormat:@"%f",self.latitude],@"lnt":[NSString stringWithFormat:@"%f",self.longitude],@"user_id":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token};
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=location" parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"error_code"] isEqualToString:@"0"]) {
//            ShowMessage(@"操作成功");
        }else{
            ShowMessage(@"操作失败");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    self.navigationController.navigationBar.hidden = YES;
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:NO animated:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.indexInter = 0;
    if (_isJpush) {
//        1 我的需求       2 我的服务         3 系统消息
        MineOrderViewController *vc = [[MineOrderViewController alloc]init];
        if ([self.stateStr isEqualToString:@"1"]) {
            vc.stateStr = @"1";
        }
        if ([self.stateStr isEqualToString:@"2"]) {
            vc.stateStr = @"2";
        }
        [self.navigationController pushViewController:vc animated:YES];
        
        if ([self.stateStr isEqualToString:@"3"]) {
            MessageAndTalkAboutViewController *VC = [[MessageAndTalkAboutViewController alloc]init];
            [self.navigationController pushViewController:VC animated:YES];
        }
        
        self.isJpush = NO;
    }
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    
    BMKCoordinateRegion region;
    region.center.latitude = self.latitude;
    region.center.longitude = self.longitude;
    _mapView.region = region;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _searcher.delegate = nil;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _subtype = 0;
//    [self WZXLaunchView];
    [self getInfoMations];
    self.navigationController.navigationBar.hidden = YES;
    HomePageTitleView *titleView = [[HomePageTitleView alloc]initWithFrame:CGRectMake(0, STATUS_HEIGHT, SCREEN_WIDTH, TITLEVIEW_HEIGHT / HEIGHT_6S_SCALE)];
    [self.view addSubview:titleView];
    self.titleView = titleView;
    self.view.backgroundColor = getColor(whiteColor);
    titleView.userImageClcik = ^{
        if (![self isLoginIn]) {
            return;
        };
        NSLog(@"头像");
        
        WJListMenuViewController *VC = [[WJListMenuViewController alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:VC];
        VC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        VC.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
        //设置模态视图弹出样式
        VC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        
        nav.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        nav.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
        //设置模态视图弹出样式
        nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        
        //创建动画
        CATransition * transition = [CATransition animation];
        //设置动画类型（这个是字符串，可以搜索一些更好看的类型）
        /*
         kCATransitionFade   交叉淡化过渡
         kCATransitionMoveIn 新视图移到旧视图上面
         kCATransitionPush   新视图把旧视图推出去
         kCATransitionReveal 将旧视图移开,显示下面的新视图
         @"pageCurl"            向上翻一页
         @"pageUnCurl"          向下翻一页
         @"rippleEffect"        滴水效果
         @"suckEffect"          收缩效果，如一块布被抽走
         @"cube"                立方体效果
         @"oglFlip"             上下翻转效果
         moveOut
         */
        transition.type = kCATransitionFade;
        //动画出现类型
        /*
         kCATransitionFromRight
         
         kCATransitionFromLeft
         
         kCATransitionFromTop
         
         kCATransitionFromBottom
         fromCenter
         */
        transition.subtype = kCATransitionFromLeft;
        //动画时间
        transition.duration = 0.5;
        //移除当前window的layer层的动画
        [self.view.window.layer removeAllAnimations];
        //将定制好的动画添加到当前控制器window的layer层
        [self.view.window.layer addAnimation:transition forKey:nil];
        
        [self presentViewController:nav animated:YES completion:nil];
        
    };
    titleView.topBtnClickBlock = ^{
        if (![self isLoginIn]) {
            return;
        };
        YXSearchServersListViewController * VC = [[YXSearchServersListViewController alloc]init];
        [self.navigationController pushViewController:VC animated:YES];
    };
    titleView.locationBtnClick = ^{
        CityListViewController *cityListView = [[CityListViewController alloc]init];
        cityListView.delegate = self;
        //热门城市列表
        cityListView.arrayHotCity = [NSMutableArray arrayWithObjects:@"广州",@"北京",@"上海",@"深圳",@"杭州", nil];
        //定位城市列表
        cityListView.arrayLocatingCity   = [NSMutableArray arrayWithObjects:@"沈阳", nil];
        
        [self presentViewController:cityListView animated:YES completion:nil];
        
    };
    titleView.newsBtnClick = ^{
        if (![self isLoginIn]) {
            return;
        };
        MessageAndTalkAboutViewController *VC = [[MessageAndTalkAboutViewController alloc]init];
        [self.navigationController pushViewController:VC animated:YES];
    };
    //1. 初始化地图
    _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, STATUS_HEIGHT + TITLEVIEW_HEIGHT / HEIGHT_6S_SCALE, SCREEN_WIDTH, SCREEN_HEIGHT - TITLEVIEW_HEIGHT / HEIGHT_6S_SCALE - STATUS_HEIGHT)];
    _mapView.layer.borderColor = [UIColor whiteColor].CGColor;
    _mapView.layer.borderWidth =  2;
    [self.view addSubview:_mapView];
/// 地图比例尺级别，在手机上当前可使用的级别为4-21级
    _mapView.zoomLevel = 18;
    ///设定地图是否现显示3D楼块效果
    _mapView.buildingsEnabled = NO;
    //2. 设置地图类型
    //切换为卫星图
//    [_mapView setMapType:BMKMapTypeStandard];
    //3. 交通图
    //打开实时路况图层
//    [_mapView setTrafficEnabled:YES];
    [self getJingWeiDu];// 定位
    // 下面的圆按钮 跳语音搜索
    // gif图片
    NSString* filePathBottom = [[NSBundle mainBundle] pathForResource:@"yuyin.gif" ofType:nil];
    NSData* imageDataBottom = [NSData dataWithContentsOfFile:filePathBottom];
    SCGIFImageView* BottomgifImageView = [[SCGIFImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 32 / WIDTH_6S_SCALE, SCREEN_HEIGHT - SafeAreaBottomHeight - 80 / HEIGHT_6S_SCALE, 65 / WIDTH_6S_SCALE, 65 / WIDTH_6S_SCALE)];
    BottomgifImageView.userInteractionEnabled = YES;
    [BottomgifImageView setData:imageDataBottom];
    UITapGestureRecognizer * imagesViewTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imagesViewTap:)];
    [BottomgifImageView addGestureRecognizer:imagesViewTapGestureRecognizer];
    [self.view addSubview:BottomgifImageView];
    
    // 隐藏百度地图Logo
    UIView *mView = _mapView.subviews.firstObject;
    for (id logoView in mView.subviews)
    {
        if ([logoView isKindOfClass:[UIImageView class]])
        {
            UIImageView *b_logo = (UIImageView*)logoView;
            b_logo.hidden = YES;
        }
    }
    // 更新版本
//    [self requestGetVersion];
}

- (void)imagesViewTap:(UITapGestureRecognizer *)tapgesture
{
    if (![self isLoginIn]) {
        return;
    };
    // CATransition动画实现
    [self pushWithAnimationType:@"fade"];
    
    YXSearchServersListViewController * VC = [[YXSearchServersListViewController alloc]init];
    [self.navigationController pushViewController:VC animated:NO];
}

// 根据城市 搜索需要搜索的东西
- (void)searchInfoMationAction
{
    //初始化搜索对象 ，并设置代理
    _searcher =[[BMKPoiSearch alloc]init];
    _searcher.delegate = self;
    //请求参数类BMKCitySearchOption
    BMKCitySearchOption *citySearchOption = [[BMKCitySearchOption alloc]init];
    citySearchOption.pageIndex = 10;
    citySearchOption.pageCapacity = 10;
    citySearchOption.city= self.currentCityStr;
    citySearchOption.keyword = self.titleNameStr;
    //发起城市内POI检索
    BOOL flag = [_searcher poiSearchInCity:citySearchOption];
    if(flag) {
        NSLog(@"城市内检索发送成功");
    }
    else {
        NSLog(@"城市内检索发送失败");
    }
}

#pragma mark implement BMKMapViewDelegate
- (void)mapViewDidFinishLoading:(BMKMapView *)mapView
{
//    mapView.zoomLevel = 18;
}
- (void)mapViewDidFinishRendering:(BMKMapView *)mapView
{
//    mapView.zoomLevel = 18;
}
/**
 *根据anntation生成对应的View
 *@param mapView 地图View
 *@param annotation 指定的标注
 *@return 生成的标注View
 */
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    NSLog(@"---------------------dujiahong");
    // 生成重用标示identifier
    NSString *AnnotationViewID = @"xidanMark";
    
    // 检查是否有重用的缓存
    BMKAnnotationView* annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    
    // 缓存没有命中，自己构造一个，一般首次添加annotation代码会运行到此处
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
        // 设置重天上掉下的效果(annotation)
        ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
    }
    if (self.indexInter >= self.dataArray.count) {
        UIImage *image = [UIImage imageNamed:@""];
        annotationView.image = image;
    }else{
        NSDictionary *dic = self.dataArray[self.indexInter];
        NSURL *url = [NSURL URLWithString:dic[@"icourl"]];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        image = [self imageWithImage:image scaledToSize:CGSizeMake(60 / WIDTH_6S_SCALE, 60 / WIDTH_6S_SCALE)];
        annotationView.image = image;
    }
    
    
//    if (self.indexInter <= self.dataArray.count) {
//        NSLog(@"%d",self.indexInter);
//        NSDictionary *dic;
//        if (self.indexInter == self.dataArray.count) {
//            dic = self.dataArray[self.indexInter - 1];
//        }else{
//            dic = self.dataArray[self.indexInter];
//        }
//        NSURL *url = [NSURL URLWithString:dic[@"icourl"]];
//        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
//        image = [self imageWithImage:image scaledToSize:CGSizeMake(60 / WIDTH_6S_SCALE, 60 / WIDTH_6S_SCALE)];
//        annotationView.image = image;
//    }
    NSLog(@"alala 多少来东方嘉盛快捷方式了%d",self.indexInter);
    // 设置位置
    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    // 单击弹出泡泡，弹出泡泡前提annotation必须实现title属性
    annotationView.canShowCallout = YES;
    // 设置是否可以拖拽
    annotationView.draggable = NO;
    self.indexInter ++;
    return annotationView;
}
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    [mapView bringSubviewToFront:view];
    [mapView setNeedsDisplay];
}
- (void)mapView:(BMKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    NSLog(@"didAddAnnotationViews");
}

#pragma mark -
#pragma mark implement BMKSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error
{
    // 清楚屏幕中所有的annotation
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    
    if (error == BMK_SEARCH_NO_ERROR) {
        NSMutableArray *annotations = [NSMutableArray array];
        for (int i = 0; i < result.poiInfoList.count; i++) {
            BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
            BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
            item.coordinate = poi.pt;
            item.title = poi.name;
            [annotations addObject:item];
        }
        [_mapView addAnnotations:annotations];
        [_mapView showAnnotations:annotations animated:YES];
    } else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR){
        NSLog(@"起始点有歧义");
    } else {
        // 各种情况的判断。。。
    }
}
#pragma mark - CityListViewDelegate
// 选择城市的时候 返回的从经纬度 self.latitude，self.longitude
- (void)didClickedWithCityName:(NSString*)cityName
{
    self.currentCityStr = cityName;
    [self.titleView.locationBtn setTitle:cityName forState:UIControlStateNormal];
    [self searchInfoMationAction];
    
    //1. 创建地理编码对象
    CLGeocoder *geocoder = [CLGeocoder new];
    
    //2. 调用地理编码方法
    [geocoder geocodeAddressString:cityName completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        //3. 根据地标对象, 获取对应的值
        
        //3.1 防错处理
        if (error || placemarks.count == 0) {
            NSLog(@"解析错误或者未解析到地址");
            return ;
        }
        
        //3.2 根据地标对象, 获取对应的值
        //CLPlacemark 地标对象
        
        //正向地理编码, 很有可能一个地名搜出多个位置, 实际开发, 应该给用户一个列表选择
        for (CLPlacemark *pm in placemarks) {
            
            NSLog(@"location: %f, %f", pm.location.coordinate.latitude, pm.location.coordinate.longitude);
            
            NSLog(@"name: %@", pm.name);
            NSLog(@"city: %@", pm.locality);
            self.latitude = pm.location.coordinate.latitude;
            self.longitude = pm.location.coordinate.longitude;
        }
        
        [self getImagesInfo];
        // 根据经纬度 地图显示位置
        BMKCoordinateRegion region;
        region.center.latitude = self.latitude;
        region.center.longitude = self.longitude;
        _mapView.region = region;
    }];
}

#pragma mark- -----------------------定位
//定位代理经纬度回调
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation * location=[locations lastObject];
    double x = location.coordinate.longitude, y =location.coordinate.latitude;
    //    NSDictionary * location_dic=@{@"latitude":[NSNumber numberWithDouble: x],@"longitude":[NSNumber numberWithDouble:y]};
    [[UserModel sharedInstanced] setlongitude:[NSString stringWithFormat:@"%f",x]];
    [[UserModel sharedInstanced] setlatitude:[NSString stringWithFormat:@"%f",y]];
    [self.locationManager stopUpdatingLocation];
    
    
    [manager stopUpdatingLocation];
//    火星坐标
    CLLocationCoordinate2D wgsPt = location.coordinate;
//    CLLocationCoordinate2D gcjPt = [JZLocationConverter wgs84ToGcj02:wgsPt];
    CLLocationCoordinate2D bdPt = [JZLocationConverter wgs84ToBd09:wgsPt];
    //当使用模拟器定位在中国大陆以外地区，计算GCJ-02坐标还是返回WGS-84
//    _pt1Lable.text = [NSString stringWithFormat:@"WGS-84(国际标准坐标)：\n %f,%f",wgsPt.latitude,wgsPt.longitude];
//    _pt2Lable.text = [NSString stringWithFormat:@"GCJ-02(中国国测局坐标(火星坐标))：\n %f,%f",gcjPt.latitude,gcjPt.longitude];
//    _pt3Lable.text = [NSString stringWithFormat:@"BD-09(百度坐标)：\n %f,%f",bdPt.latitude,bdPt.longitude];
    
    CLLocation *newLocation = locations[0];
    self.latitude = bdPt.latitude;// 维度
    self.longitude = bdPt.longitude; // 精度
    BMKCoordinateRegion region;
    region.center.latitude = self.latitude;
    region.center.longitude = self.longitude;
    _mapView.region = region;
    
    [self getImagesInfo];// 获取大头针图片
    [self postLatAndLongToServer];
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];
            
            //获取城市
            NSString *city = placemark.locality;
            if (!city) {
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                city = placemark.administrativeArea;
            }
            [self.titleView.locationBtn setTitle:city forState:UIControlStateNormal];
            [[UserModel sharedInstanced] setAddress:city];
            self.currentCityStr = city;
            NSLog(@"city = %@", city);//沈阳市
            NSLog(@"--%@",placemark.name);//黄河大道221号
            NSLog(@"++++%@",placemark.subLocality); //浑南区
            NSLog(@"country == %@",placemark.country);//中国
            NSLog(@"administrativeArea == %@",placemark.administrativeArea); //辽宁省
            NSString *addressStr = [NSString stringWithFormat:@"%@ %@ %@ %@",placemark.administrativeArea,city,placemark.subLocality,placemark.name];
            [UserModel sharedInstanced].locationAddress = addressStr;
        }
        else if (error == nil && [array count] == 0)
        {
            NSLog(@"No results were returned.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
}
//执行经纬度代理方法
- (void)getJingWeiDu{
    self.locationManager=[[CLLocationManager alloc]init];
    //期望精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    //大约变化10米更新一次
    //    self.locationManager.distanceFilter=10;
    //认证NSLocationAlwaysUsageDescription
//    /6. 期望精准度
    //desired: 期望/渴望   Accuracy: 精准度
    
    //iOS定位的方式: GPS(全球卫星定位系统, 跟24颗卫星通讯) / WIFI / 移动基站(手机网络). 系统会自动调用以上方式定位
    //定位越精准, 耗电量越高
    
    /*
     CLLocationAccuracy kCLLocationAccuracyBestForNavigation      最好的为导航用的
     CLLocationAccuracy kCLLocationAccuracyBest;                  最好的
     CLLocationAccuracy kCLLocationAccuracyNearestTenMeters;      十米
     CLLocationAccuracy kCLLocationAccuracyHundredMeters;         百米
     CLLocationAccuracy kCLLocationAccuracyKilometer;             千米
     CLLocationAccuracy kCLLocationAccuracyThreeKilometers;       三千米
     **/
    if([[UIDevice currentDevice] systemVersion].doubleValue>8.0)//如果ios是8.0以上版本
    {
        if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])//位置管理对象中有requestAlwaysAuthorization这个行为
        {
            //执行经纬度代理方法
            [self.locationManager requestAlwaysAuthorization];
        }
    }
    
    self.locationManager.delegate=self;
    [self.locationManager startUpdatingLocation];
}
// 修改图片大小
- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
// 获取版本号
//- (void)requestGetVersion{
//    // 当前应用软件版本
//    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
//    NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
//    NSLog(@"当前应用软件版本:%@",appCurVersion);
//
//    NSDictionary *parameter = @{@"uid":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token,@"platform":@"1"};
//    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=getversion" parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        if ([responseObject[@"error_code"] isEqualToString:@"0"]) {
//            if(![responseObject[@"data"][@"version"] isEqualToString:appCurVersion]){
//                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"发现新版本！" message:@"立即前往更新！" preferredStyle:UIAlertControllerStyleAlert];
//                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"稍后再说" style:UIAlertActionStyleCancel handler:nil];
//                UIAlertAction *updateAction = [UIAlertAction actionWithTitle:@"立即更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                    // 跳转APP Store
////                    NSString *str = [NSString stringWithFormat: @"https://itunes.apple.com/cn/app/%E4%B8%96%E9%BE%99%E5%AE%9E%E4%B8%9A/id1271271968?mt=8"];
//                    NSString *str = [NSString stringWithFormat:responseObject[@"data"][@"url"]];
//                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
//                }];
//                [alert addAction:cancelAction];
//                [alert addAction:updateAction];
//                [self presentViewController:alert animated:YES completion:nil];
//            }
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [self showError:error];
//    }];
//
//}

- (NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [NSMutableArray array].mutableCopy;
    }
    return _dataArray;
}

@end
